package com.globallogic.restdemo.dao;

import com.globallogic.restdemo.dto.User;
import com.globallogic.restdemo.utils.IdGenerator;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class UserDao {

    private static UserDao instance;

    public static UserDao getInstance(){
        if (instance == null){
            synchronized(UserDao.class) {
                UserDao inst = instance;
                if (inst == null) {
                    synchronized(UserDao.class) {
                        instance = new UserDao();
                    }
                }
            }
        }
        return instance;
    }

    private Map<Long, User> users = new HashMap<Long, User>();

    private UserDao(){
        User user1 = new User("john.doe@gmail.com", "John", "Doe");
        User user2 = new User("jane.doe@gmail.com", "Jane", "Doe");

        addUser(user1);
        addUser(user2);
    }

    public Collection<User> getAllUsers(){
        return  users.values();
    }

    public User getUserById(long id){
        return users.get(id);
    }

    public void addUser(User user){
        user.setId(IdGenerator.generateId());
        users.put(user.getId(), user);
    }

    public void updateUser(User user){
        users.put(user.getId(), user);
    }

    public void removeAllUsers(){
        users = new HashMap<Long, User>();
    }

    public void removeUserById(long id){
        users.remove(id);
    }
}
